package cn.touna.jss.common.mock;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;

/**
 * Created by wuwc on 2017/5/16.
 */
//@Component
public class TemplateUtil {

    private String configPath;

    public Template getTemplate(String mockSwitch, String dynamicVariableValue) throws IOException {
        StringBuffer filePathSb = new StringBuffer();
        filePathSb.append(configPath);
        filePathSb.append(File.separator);
        filePathSb.append("templates");
        filePathSb.append(File.separator);
        filePathSb.append(mockSwitch);
        filePathSb.append("@");
        filePathSb.append(dynamicVariableValue != null ? dynamicVariableValue : "");
        filePathSb.append(".template");
        String filePath = filePathSb.toString();
        File file = new File(filePath);
        InputStream stream = file.exists() ? new FileInputStream(file) : TemplateUtil.class.getResourceAsStream(filePath);
        BufferedReader br = new BufferedReader(new InputStreamReader(stream));
        StringBuffer dataTemplate = new StringBuffer();
        String data;
        while ((data = br.readLine()) != null) {
            dataTemplate.append(data);
        }

        br.close();
        stream.close();

        StringTemplateLoader stringLoader = new StringTemplateLoader();
        String templateContent = dataTemplate.toString();
        stringLoader.putTemplate(file.getName(), templateContent);
        Configuration cfg = new Configuration();
        cfg.setTemplateLoader(stringLoader);
        Template template = cfg.getTemplate(file.getName());
        return template;
    }


    public static String process(Template template, Object obj) throws IOException, TemplateException {
        /*StringBuilderWriter writer = new StringBuilderWriter();
        template.process(obj, writer);
        return writer.toString();*/
        return "";
    }

}
